# coding:utf-8
# admin.py
from myblog.model.comment import Comment
from flask import Blueprint, render_template, request
from sqlalchemy.sql.expression import label
from myblog.model.article import Article
from myblog.model.comment import Comment
import json
from myblog.model.label import Label
from sqlalchemy import func
from myblog import db
from flask import request, jsonify, session
articleController = Blueprint('article', __name__)


@articleController.route('/getarticlelist')
def getArticleList():
    print(11111111111111111111111111111111111111111111111111111111111111111111111111)
    print(session.get('username'))
    s = Article.query.all()
    print(s)
    articles = []
    for i in s:
        s2 = db.session.query(Label).filter(Label.article_id == i.id).all()
        label = []
        for value in s2:
            label.append(value.label)
        print(label)
        articles.append({'id': i.id, 'title': i.title,
                        "content": i.content, "imgSrc": i.imgSrc, "label": label,"create_at":i.create_at})
    return jsonify({'data': articles, 'meta': {"code": 200, "msg": "请求成功！！！"}})


@articleController.route('/getonearticle/<id>')
def getonearticle(id):
        s = Article.query.filter(Article.id==int(id)).first()
        last =db.session.query(Article.title,Article.id).filter(Article.id==int(id)-1).first()
        nextA =db.session.query(Article.title,Article.id).filter(Article.id==int(id)+1).first()
        s2 = db.session.query(Label).filter(Label.article_id == int(id)).all()
        count = db.session.query(Article).count()

        label=[]
        for value in s2:
            label.append(value.label)
    
        s3 = Comment.query.filter(Comment.article_id == int(id))
        contents = []
        for value in s3:
            contents.append({"id": value.id, "visitor_name": value.visitor_name,
                            "content": value.content,"create_at":value.create_at})
        if int(id)-1==0:
            articles = {'id': s.id, 'title': s.title,
                        "content": s.content, "imgSrc": s.imgSrc, "label": label,
                        "create_at":s.create_at,'contents':contents,'last':{'id':'','title':''},
                        'next':{'id':nextA.id,'title':nextA.title}
                        }
        elif int(id)+1 ==count+1:articles = {'id': s.id, 'title': s.title,
                        "content": s.content, "imgSrc": s.imgSrc, "label": label,
                        "create_at":s.create_at,'contents':contents,'last':{'id':last.id,'title':last.title},
                        'next':{'id':'','title':''}
                        }  
        else:articles = {'id': s.id, 'title': s.title,
                        "content": s.content, "imgSrc": s.imgSrc, "label": label,
                        "create_at":s.create_at,'contents':contents,'last':{'id':last.id,'title':last.title},
                        'next':{'id':nextA.id,'title':nextA.title}
                        }               
        return jsonify({'data': articles, 'meta': {"code": 200, "msg": "请求成功！！！"}})



@articleController.route('/addarticle', methods=['POST'])
def addarticle():
    data = json.loads(request.get_data(as_text=True))
    title = data['title']  # 用户名
    content = data['content']  # 密码
    imgSrc = data['imgSrc']  # 背景图
    label = data['label']  # 标签
    if title and content:
        db.session.add(
            Article(title=title, content=content, imgSrc=imgSrc))
        s = db.session.commit()

        result = db.session.query(Article).order_by(Article.id.desc()).filter(
            Article.title == title and Article.content == content and Article.imgSrc == imgSrc).first()
        if label:
            for key in label:
                db.session.add(Label(label=key, article_id=result.id))
            db.session.commit()
        return jsonify({'data': {}, 'meta': {"code": 200, "msg": "添加文章成功！"}})
    else:
        return jsonify({'data': {}, 'meta': {"code": 403, "msg": "内容或标题没定义"}})


@articleController.route('/updatearticle/<id>', methods=['POST'])
def updatearticle(id):
        data = json.loads(request.get_data(as_text=True))
        title = data['title']  # 用户名
        content = data['content']  # 密码
        imgSrc = data['imgSrc']  # 背景图
        label = data['label']  # 标签
        print(label)
        print(title)

        print(content)

        print(imgSrc)


        if title and content:
            article = Article.query.filter(Article.id == int(id)).first()
            article.title = title
            article.content = content
            article.imgSrc = imgSrc
            db.session.commit()
        if label:
            db.session.query(Label).filter(
                Label.article_id == int(id)).delete()
            db.session.commit()
            for key in label:
                db.session.add(Label(label=key, article_id=int(id)))
            db.session.commit()
            return jsonify({'data': {}, 'meta': {"code": 200, "msg": "修改文章成功！"}})
        return jsonify({'data': {}, 'meta': {"code": 403, "msg": "内容或标题没定义"}})


@articleController.route('/removearticle/<id>')
def removearticle(id):
        db.session.query(Article).filter(Article.id == int(id)).delete()
        db.session.commit()
        db.session.query(Label).filter(
            Label.article_id == int(id)).delete()
        db.session.commit()
        return jsonify({'data': {}, 'meta': {"code": 200, "msg": "删除文章成功！"}})


@articleController.route('/getlabel')
def getlabel():
    s = db.session.query(Label.label, func.count(
        Label.label)).group_by(Label.label).all()
    total = []
    for (label, count) in s:
        total.append({"label": label, "count": count})
    print(total)
    return jsonify({'data': total, 'meta': {"code": 200, "msg": "获取标签成功！"}})


@articleController.route('/searchlabel/<label>')
def searchlabel(label):
    article_id = db.session.query(Label.article_id).filter(
        Label.label == label).distinct().all()
    article_arr = []
    print(article_id)
    for (value,) in article_id:
        article_arr.append(int(value))
    print(article_arr)
    s = Article.query.filter(Article.id.in_(article_arr))
    print(s)
    articles = []
    for i in s:
        s2 = db.session.query(Label).filter(Label.article_id == i.id).all()
        label = []
        for value in s2:
            label.append(value.label)
        print(label)
        articles.append({'id': i.id, 'title': i.title,
                        "content": i.content, "imgSrc": i.imgSrc, "label": label,"create_at":i.create_at})
    return jsonify({'data': articles, 'meta': {"code": 200, "msg": "标签分类显示！"}})


@articleController.route('/addcomment', methods=['POST'])
def addcomment():
    data = json.loads(request.get_data(as_text=True))
    content = data['content']  # 用户名
    visitor_name = data['visitor_name']  # 密码
    article_id = data['article_id']  # 背景图
    db.session.add(
        Comment(content=content, visitor_name=visitor_name, article_id=article_id))
    db.session.commit()
    return jsonify({'data': {}, 'meta': {"code": 200, "msg": "评论发表成功！"}})


@articleController.route('/searchcontent/<id>')
def searchcontent(id):
    print(id)
    s = Comment.query.filter(Comment.article_id == int(id))
    contents = []
    for value in s:
        contents.append({"id": value.id, "visitor_name": value.visitor_name,
                        "content": value.content})
    print(contents)
    return jsonify({'data': contents, 'meta': {"code": 200, "msg": "查询评论成功！"}})


@articleController.route('/removecontent/<id>', methods=['POST'])
def removecontent(id):
    db.session.query(Comment).filter(
        Comment.id == int(id)).delete()
    db.session.commit()
    return jsonify({'data': {}, 'meta': {"code": 200, "msg": "删除评论成功"}})

@articleController.route('/getcomment')
def getcomment():
    s = Comment.query.order_by(Comment.create_at.desc()).all()
    contents = []
    for value in s:
        contents.append({"id": value.id, "visitor_name": value.visitor_name,
                        "content": value.content,"article_id":value.article_id,'create_at':value.create_at})
    print(contents)
    return jsonify({'data': contents, 'meta': {"code": 200, "msg": "查询评论成功！"}})